package com.yy.job.core.config;

import java.io.InputStream;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.yy.job.core.config.validator.ProjectXmlConfigValidator;
import com.yy.job.core.config.xml.ProjectXmlConfig;
import com.yy.job.utils.JaxbUtils;

/**
 * yy-job的xml文件配置初始化
 * 
 * @author eleven.li
 *
 */
@Component
public class JobConfigXmlContext {

	private static final Logger log = LoggerFactory.getLogger(JobConfigXmlContext.class);

	/**
	 * job-xml内容
	 */
	private ProjectXmlConfig projectXmlConfig;

	/**
	 * yy-job配置的任务列表xml文件
	 */
	@Value("${yy-job.configPath:yy-job-config.xml}")
	private String configPath;

	@PostConstruct
	public void initConfig() {
		if (StringUtils.isBlank(this.configPath)) {
			log.warn("yy-job configPath is empty, do not start yy-job");
			return;
		}
		InputStream configIn = JobConfigXmlContext.class.getClassLoader().getResourceAsStream(this.configPath);
		projectXmlConfig = (ProjectXmlConfig) JaxbUtils.converyToJavaBean(configIn, ProjectXmlConfig.class);
		log.info("yy-job config xml content：{}", JSON.toJSONString(projectXmlConfig));

		// 校验job配置文件是否正确
		ProjectXmlConfigValidator.validate(projectXmlConfig);
		
		// 初始化一些数据结构，方便后续查找配置项
		projectXmlConfig.build();
	}

	public ProjectXmlConfig getProjectXmlConfig() {
		return projectXmlConfig;
	}

}
